<?php

namespace app\common\library;

use think\Hook;
use app\api\library\SendSms;
use think\Db;
/**
 * 短信验证码类
 */
class Sms
{

    /**
     * 验证码有效时长
     * @var int
     */
    protected static $expire = 900;

    /**
     * 最大允许检测的次数
     * @var int
     */
    protected static $maxCheckNums = 10;

    /**
     * 获取最后一次手机发送的数据
     *
     * @param   int    $mobile 手机号
     * @param   string $event  事件
     * @return  Sms
     */
    public static function get($mobile, $event = 'default')
    {
        $sms = \app\common\model\Sms::
        where(['mobile' => $mobile, 'event' => $event])
            ->order('id', 'DESC')
            ->find();
        Hook::listen('sms_get', $sms, null, true);
        return $sms ? $sms : null;
    }

    /**
     * 发送验证码
     *
     * @param   int    $mobile 手机号
     * @param   int    $code   验证码,为空时将自动生成4位数字
     * @param   string $event  事件
     * @return  boolean
     */
    public static  function send($mobile, $code = null, $event = 'default',$terrace)
    {
        $code = is_null($code) ? mt_rand(1000, 9999) : $code;
        $time = time();
        $ip = request()->ip();
        /*$sms = \app\common\model\Sms::create(['event' => $event, 'mobile' => $mobile, 'code' => $code, 'ip' => $ip, 'createtime' => $time]);*/

        $data['mobile'] = $mobile;
        //$data['content'] = '您的验证码'.$code.'，该验证码3分钟内有效，请勿泄漏于他人！如非本人操作，请忽略此短信。';
        $data['content'] = '您的验证码是'.$code;
        $result = SendSms::singleSend($data,$terrace);
		if ($result['result'] == 0){
		    $time = time();
		    $ip = request()->ip();
					// if($event == 'default'){
					// 	//发送成功之后把卡密改成已发送 如果是给用户发送卡密和网址的
					// 	$da['is_send'] = 2;
					// 	$da['mobile'] = $mobile;
					// 	Db::name('cdkey')->where('is_del',1)->where('coupon_code_psd',$code)->update($da);
					// }
		    $sms = \app\common\model\Sms::create(['event' => $event, 'mobile' => $mobile, 'code' => $code, 'ip' => $ip, 'createtime' => $time]);
		    if (! $sms) {
		        $sms->delete();
		        return false;
		    }
				// $re['event'] = $event;
				$re['mobile'] = $mobile;
				// $re['code'] = $code;
				$re['content'] = json_encode($result);
				$re['createtime'] = time();
				Db::name('sms_send')->insert($re);
		    return true;
		}else{
			// $da['event'] = $event;
		    $da['mobile'] = $mobile;
		    // $da['code'] = $code;
		    $da['content'] = json_encode($result);
		    $da['createtime'] = time();
		    Db::name('sms_send')->insert($da);
		    return false;
		}
       /* if (!$result) {
            $sms->delete();
            return false;
        }
        return true;*/
    }

    /**
     * 发送通知
     *
     * @param   mixed  $mobile   手机号,多个以,分隔
     * @param   string $msg      消息内容
     * @param   string $template 消息模板
     * @return  boolean
     */
    public static function notice($mobile, $msg = '', $template = null)
    {
        $params = [
            'mobile'   => $mobile,
            'msg'      => $msg,
            'template' => $template
        ];
        $result = Hook::listen('sms_notice', $params, null, true);
        return $result ? true : false;
    }

    /**
     * 校验验证码
     *
     * @param   int    $mobile 手机号
     * @param   int    $code   验证码
     * @param   string $event  事件
     * @return  boolean
     */
    public static function check($mobile, $code, $event = 'default')
    {

        $sms = \app\common\model\Sms::where(['mobile' => $mobile, 'event' => $event])
            ->order('id', 'DESC')
            ->find();
        $time =$sms['createtime'] + self::$expire;

        if ($sms) {
            if ($time > time() && $sms['times'] <= self::$maxCheckNums) {
                if($code!= $sms['code']){
                    return false;
                }
                if ($code== $sms['code']) {
                    $sms->times = $sms->times + 1;
                    $sms->save();
                    return true;
                }
            } else {
                // 过期则清空该手机验证码
                self::flush($mobile, $event);
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 清空指定手机号验证码
     *
     * @param   int    $mobile 手机号
     * @param   string $event  事件
     * @return  boolean
     */
    public static function flush($mobile, $event = 'default')
    {
        \app\common\model\Sms::
        where(['mobile' => $mobile, 'event' => $event])
            ->delete();
        Hook::listen('sms_flush');
        return true;
    }
}
